<template>
	<hyb-page title="结算">
		<template v-slot:body>
			<view class="pay-container gui-padding">
				<view @tap="goAddress()" style="margin-top: -20rpx;"
					class="gui-bg-white gui-flex pay-card-radius gui-align-items-center gui-space-between gui-padding">
					<view class="gui-text gui-color-gray">
						<view class="gui-flex">
							<gui-tags text="请选择收货地址" :size="22"></gui-tags>
							<text>{{address.d_uname}} {{address.d_phone}}</text>
						</view>

						<view>
							{{address.d_address}}{{address.d_xxaddress}}
						</view>

					</view>

					<view><text class="gui-icons gui-block gui-color-gray gui-text">&#xe601;</text></view>
				</view>


				<view v-for="(info,index) in mergedList" :key="index" style="margin-top: -20rpx;">
					<view
						class="gui-bg-white gui-margin-top gui-flex pay-card-radius gui-align-items-center gui-padding">
						<image v-if="!$store.state.base.show_base.jy_bb" :src="info.goods.g_thumb"
							style="height: 160rpx;width: 160rpx;" mode="aspectFit"></image>
						<view class="gui-text gui-flex1 gui-margin-x">
							<view class="gui-flex">
								<text>{{info.goods.g_name}}</text>
							</view>

							<view v-for="(spec, i) in (expandedItems[index] ? info.specs : info.specs.slice(0, 2))"
								:key="i" class="gui-color-gray gui-margin-top-small gui-text-small">
								{{spec.name}} ×{{spec.num}} <span
									style="color:#f00">￥{{format_money(spec.price)}}</span>
							</view>

							<!-- 展开/收起按钮 -->
							<view v-if="info.specs.length > 2" class="gui-margin-top-small">
								<text @tap="toggleSpecs(index)" class="gui-color-blue gui-text-small">
									{{ expandedItems[index] ? '收起' : `查看全部${info.specs.length}个规格` }}
								</text>
							</view>

							<view v-if="info.extra1 && info.extra1.length"
								class="gui-color-blue gui-margin-top-small gui-text-small">
								其他费用：
								<span v-for="(item, i) in info.extra1" :key="i">{{item.name}} </span>
							</view>

							<view v-if="info.extra2 && info.extra2.length"
								class="gui-color-green gui-margin-top-small gui-text-small">
								增值费用：
								<span v-for="(item, i) in info.extra2" :key="i">{{item.name}} </span>
							</view>

							<view class="gui-color-red gui-margin-top-small gui-text-right gui-bold">
								￥{{ format_money(info.specs.reduce((sum, spec) => sum + spec.price * spec.num, 0)) }}
							</view>
						</view>
					</view>

					<view class="gui-bg-white gui-margin-top pay-card-radius"
						v-if="info.goods.g_extra1 || info.goods.g_extra2">
						<view v-if="info.goods.g_extra1 && info.goods.g_extra1.length > 0">
							<view class="gui-padding-small gui-border-b gui-color-gray">
								{{ info.goods.extra1_name || '其他费用' }}
								<text class="gui-icons gui-color-blue gui-margin-left"
									@tap="showTip(info.goods.extra1_name || '其他费用', info)"
									style="font-size: 32rpx;">&#xe646;</text>
							</view>
							<view class="gui-flex gui-border-t gui-align-items-center gui-space-between gui-padding-y"
								v-for="(item,index1) in info.goods.g_extra1" :key="index1">
								<view class="gui-flex gui-align-items-center gui-justify-content-end">
									<text class="gui-text gui-primary-text gui-margin-x">{{item.name}}:</text>
									<view class="gui-text-small gui-primary-color">￥ {{Number(item.price).toFixed(2)}}元
									</view>
								</view>
								<gui-radio @change="extra1Change(info,index1)"
									:checked="info.extra1 && info.extra1.indexOf(index1) != -1"
									:defaultClass="['gui-color-gray']"
									:checkedClass="['gui-bg-blue', 'gui-color-white']">
								</gui-radio>
							</view>
						</view>
						<view v-if="info.goods.g_extra2 && info.goods.g_extra2.length > 0">
							<view class="gui-padding-small gui-border-b gui-color-gray">
								{{ info.goods.extra2_name || '增值费用' }}
								<text class="gui-icons gui-color-blue gui-margin-left"
									@tap="showTip(info.goods.extra2_name || '增值费用', info)"
									style="font-size: 32rpx;">&#xe646;</text>
							</view>
							<view class="gui-flex gui-border-t gui-align-items-center gui-space-between gui-padding-y"
								v-for="(item,index2) in info.goods.g_extra2" :key="index2">
								<view class="gui-flex gui-align-items-center gui-justify-content-end">
									<text class="gui-text gui-primary-text gui-margin-x">{{item.name}}:</text>
									<view class="gui-text-small gui-primary-color">￥ {{Number(item.price).toFixed(2)}}元
									</view>
								</view>
								<gui-radio @change="extra2Change(info,index2)"
									:checked="info.extra2 && info.extra2.indexOf(index2) != -1"
									:defaultClass="['gui-color-gray']"
									:checkedClass="['gui-bg-blue', 'gui-color-white']">
								</gui-radio>
							</view>
						</view>
					</view>
				</view>





				<view class="gui-bg-white pay-card-radius gui-padding"
					v-if="$store.state.base.show_base.thd || $store.state.base.show_base.cph || $store.state.base.show_base.sp_beizhu">
					<view class="gui-flex gui-align-items-center" v-if="$store.state.base.show_base.thd">
						<view style="width: 140rpx;">提货单</view>
						<input v-model="extra.bill_num" class="gui-flex1 gui-border-b gui-margin-x gui-padding-y-small"
							placeholder="请输入提货单" />
					</view>

					<view class="gui-flex gui-margin-top gui-align-items-center" v-if="$store.state.base.show_base.cph">
						<view style="width: 140rpx;">车牌号</view>
						<input v-model="extra.truck_num" class="gui-flex1 gui-border-b gui-margin-x gui-padding-y-small"
							placeholder="请输入车牌号" />
					</view>

					<view class="gui-flex  gui-align-items-start" style="margin-top: -5rpx;"
						v-if="$store.state.base.show_base.sp_beizhu">
						<view style="width: 140rpx; margin-top: 10rpx;">备注</view>
						<textarea v-model="extra.remark" class="gui-flex1 gui-border" placeholder="请输入备注"
							style="height: 200rpx; border-radius: 15rpx; resize: none; margin-left: -60rpx; padding: 15rpx;"
							maxlength="100" />
					</view>
				</view>


			</view>





			<hyb-pay ref="hybPay" :yhq="true" :max_jifen="maxJifen" :money="money + extraMoney"
				:discount_money="discount_money + extra_discount_money" :yunfei="yunfei" @confirm="confirm"></hyb-pay>

		</template>
	</hyb-page>
</template>

<script>
	import moment from 'moment';
	export default {
		data() {
			return {
				address: {},
				guige: -1,
				num: 1,
				tag: "pay",
				is_vip: false,
				money: 0,
				extraMoney: 0,
				discount_money: 0,
				extra_discount_money: 0,
				userinfo: {},
				list: [],
				maxJifen: 0,
				items: [],
				yunfei: 0,
				extra: {},
				extra1: [],
				extra2: [],
				expandedItems: {}, // 管理每个商品的展开状态
				isSubmitting: false, // 防止重复提交的标志
				lastPayType: null, // 记录上次使用的支付方式
			}
		},
		async onLoad(options) {

			// 检查是否禁用接口调用
			if (this.$store.state.base.show_base && this.$store.state.base.show_base.jy_bb === 1) {
				// 当jy_bb=1时，不调用接口，使用默认值或缓存数据
				this.userinfo = uni.storage.get("userinfo") || {};
				this.is_vip = this.userinfo.huiyuan || false;
			} else {
				// 正常调用接口
				this.userinfo = await uni.gPost("user/info");
				uni.storage.set("userinfo", this.userinfo);

				if (this.userinfo.huiyuan) {
					this.is_vip = true;
				}
			}

			let list = uni.storage.get("goods_list");

			// 批量获取最新的商品数据，避免多次调用接口
			try {
				// 收集所有商品ID
				const goodsIds = list.map(item => item.goods.g_id);

				// 批量获取商品信息
				const freshGoodsList = await uni.gPost("goods/batch_info", {
					ids: goodsIds
				});

				// 创建商品ID到商品信息的映射
				const goodsMap = {};
				freshGoodsList.forEach(goods => {
					goodsMap[goods.g_id] = goods;
				});

				// 更新商品数据，保持原有的规格选择
				list.forEach(item => {
					if (goodsMap[item.goods.g_id]) {
						item.goods = goodsMap[item.goods.g_id];
					}
				});
			} catch (error) {
				// 批量获取失败时使用原有数据
			}

			list.forEach(item => {
				item.extra1 = []
				item.extra2 = []
			})
			this.list = list

			// 检查是否禁用接口调用
			uni.gPost("address/list").then((list) => {
				if (list.length > 0) {
					this.address = list[0]
				}
			})

			uni.$on(this.tag, (address) => {
				this.address = address;
			})

			// 重新计算基础价格，使用最新的商品数据
			this.money = 0;
			this.discount_money = 0;
			this.maxJifen = 0;
			this.yunfei = 0;

			this.list.forEach((item) => {
				this.maxJifen += parseFloat(item.goods.g_jifen);
				this.yunfei += parseInt(item.goods.g_yunfei);

				let originalPrice = 0;
				if (item.guige_index == -1) {
					originalPrice = item.goods.g_jiage * item.g_num;
				} else {
					originalPrice = item.goods.g_guigecontent[item.guige_index]["price"] * item.g_num;
				}
				// 会员价格计算
				const zhekou = (this.userinfo.huiyuan_xq && this.userinfo.huiyuan_xq.h_zhekou) ? this.userinfo
					.huiyuan_xq.h_zhekou : 1;
				if (this.is_vip && zhekou) {
					let memberPrice = 0;
					if (item.guige_index == -1) {
						// 无规格商品
						if (item.goods.vip_jiage > 0) {
							memberPrice = item.goods.vip_jiage * item.g_num;
						} else {
							memberPrice = item.goods.g_jiage * item.g_num * zhekou;
						}
					} else {
						// 有规格商品
						const specVipPrice = item.goods.g_guigecontent[item.guige_index].vip_price;
						if (specVipPrice > 0) {
							memberPrice = specVipPrice * item.g_num;
						} else {
							memberPrice = item.goods.g_guigecontent[item.guige_index].price * item.g_num *
								zhekou;
						}
					}
					this.money += memberPrice;
					this.discount_money += originalPrice - memberPrice;
				} else {
					// 非会员，使用原价
					this.money += originalPrice;
				}

				this.items.push({
					c_id: item.goods.c_id,
					g_id: item.goods.g_id,
					s_id: item.goods.g_s_id,
					g_num: item.g_num,
					guige_index: item.guige_index,
					extra1: item.extra1 || [],
					extra2: item.extra2 || [],
					// 添加跳转链接信息，用于保存到订单数据库
					extra1_tip: item.goods.g_extra1 && item.goods.g_extra1[0] ? item.goods.g_extra1[0]
						.tip : '',
					extra2_tip: item.goods.g_extra2 && item.goods.g_extra2[0] ? item.goods.g_extra2[0]
						.tip : ''
				})
			})

		},

		methods: {

			extra1Change(info, index) {
				const index1 = info.extra1.indexOf(index)
				if (index1 == -1) {
					info.extra1.push(index)
				} else {
					info.extra1.splice(index1, 1)
				}

				// 同步更新原始list数据
				info._itemIndexes.forEach(itemIndex => {
					if (!this.list[itemIndex].extra1) {
						this.list[itemIndex].extra1 = [];
					}
					this.list[itemIndex].extra1 = [...info.extra1];
				});

				this.setExtraMoney()
			},

			extra2Change(info, index) {
				const index1 = info.extra2.indexOf(index)
				if (index1 == -1) {
					info.extra2.push(index)
				} else {
					info.extra2.splice(index1, 1)
				}

				// 同步更新原始list数据
				info._itemIndexes.forEach(itemIndex => {
					if (!this.list[itemIndex].extra2) {
						this.list[itemIndex].extra2 = [];
					}
					this.list[itemIndex].extra2 = [...info.extra2];
				});

				this.setExtraMoney()
			},

			setExtraMoney() {
				let totalExtraPrice = 0;
				let totalMemberPrice = 0;
				let totalDiscount = 0;
				const zhekou = (this.userinfo.huiyuan_xq && this.userinfo.huiyuan_xq.h_zhekou) ? this.userinfo.huiyuan_xq
					.h_zhekou : 1;

				// 检查是否按数量计算增值费用费
				const calculateByQuantity = this.$store.state.base.show_base.sp_fzfwf;

				this.mergedList.forEach((info) => {
					// 计算该商品的总数量
					let totalQuantity = 0;
					info.specs.forEach(spec => {
						totalQuantity += spec.num;
					});

					// 其他费用费用计算
					if (info.extra1 && info.extra1.length > 0 && info.goods.g_extra1) {
						info.extra1.forEach(index => {
							const item = info.goods.g_extra1[index];
							if (item) {
								const originalPrice = Number(item.price);
								if (this.is_vip && zhekou) {
									let memberPrice = item.vip_price > 0 ? Number(item.vip_price) :
										originalPrice * zhekou;
									// 根据配置决定是否按数量计算
									const multiplier = calculateByQuantity ? totalQuantity : 1;
									totalMemberPrice += memberPrice * multiplier;
									totalDiscount += (originalPrice - memberPrice) * multiplier;
								} else {
									// 根据配置决定是否按数量计算
									const multiplier = calculateByQuantity ? totalQuantity : 1;
									totalMemberPrice += originalPrice * multiplier;
								}
							}
						});
					}
					// 增值费用费用计算
					if (info.extra2 && info.extra2.length > 0 && info.goods.g_extra2) {
						info.extra2.forEach(index => {
							const item = info.goods.g_extra2[index];
							if (item) {
								const originalPrice = Number(item.price);
								if (this.is_vip && zhekou) {
									let memberPrice = item.vip_price > 0 ? Number(item.vip_price) :
										originalPrice * zhekou;
									// 根据配置决定是否按数量计算
									const multiplier = calculateByQuantity ? totalQuantity : 1;
									totalMemberPrice += memberPrice * multiplier;
									totalDiscount += (originalPrice - memberPrice) * multiplier;
								} else {
									// 根据配置决定是否按数量计算
									const multiplier = calculateByQuantity ? totalQuantity : 1;
									totalMemberPrice += originalPrice * multiplier;
								}
							}
						});
					}
				});

				this.extraMoney = totalMemberPrice;
				this.extra_discount_money = totalDiscount;

			},

			// payChange(type) {
			// 	this.pay_type = type;
			// 	if (type == 0 && this.userinfo.u_money < this.total_money) {
			// 		uni.showToast({
			// 			title: "可用余额不足,请先充值",
			// 			icon: "none"
			// 		})
			// 		this.$nextTick(() => {
			// 			this.pay_type = 1;
			// 		})
			// 	}

			// 	if (type == 1) {
			// 		this.pay_type = -1;
			// 		this.$nextTick(() => {
			// 			this.pay_type = 1;
			// 		})
			// 	}
			// },

			format_money(val) {
				return parseFloat(val).toFixed(2);
			},




			goJishi() {
				uni.navigateTo({
					url: "/hyb_o2o/jishi/list/list?tag=1"
				})
			},

			goAddress() {
				uni.navigateTo({
					url: "/hyb_o2o/address/address?flag=1&tag=" + this.tag
				})
			},

			confirm(pay_type, jifen, yhq_id, jb_yusuan, pay_u_id) {
				// 防止重复提交 - 但允许切换支付方式
				if (this.isSubmitting && this.lastPayType === pay_type) {
					uni.showToast({
						title: "正在处理中，请勿重复提交",
						icon: 'none'
					});
					return;
				}

				if (!this.address.d_id) {
					uni.showToast({
						title: "请选择地址",
						icon: 'none'
					})
				} else if (!this.extra.bill_num && false) {
					uni.showToast({
						title: "请输入提货单",
						icon: 'none'
					})
				} else if (!this.extra.truck_num && false) {
					uni.showToast({
						title: "请输入车牌号",
						icon: 'none'
					})
				} else {
					// 设置提交状态
					this.isSubmitting = true;
					this.lastPayType = pay_type; // 记录当前支付方式

					// 显示加载提示
					uni.showLoading({
						title: '正在提交订单...',
						mask: true
					});

					// 更新items数据，确保包含最新的增值费用和其他费用选择
					this.items.forEach((item, index) => {
						item.extra1 = this.list[index].extra1 || [];
						item.extra2 = this.list[index].extra2 || [];
						// 同时更新跳转链接信息
						item.extra1_tip = this.list[index].goods.g_extra1 && this.list[index].goods.g_extra1[0] ?
							this.list[index].goods.g_extra1[0].tip : '';
						item.extra2_tip = this.list[index].goods.g_extra2 && this.list[index].goods.g_extra2[0] ?
							this.list[index].goods.g_extra2[0].tip : '';
					});

					uni.$pay.pay("pay/goods", {
						extra: this.extra,
						pay_u_id: pay_u_id,
						address_id: this.address.d_id,
						items: this.items,
						jifen: jifen
					}, pay_type).then(() => {
						// 隐藏加载提示
						uni.hideLoading();

						// 重置提交状态
						this.isSubmitting = false;
						this.lastPayType = null; // 重置支付方式记录

						// 重置支付组件的提交状态
						if (this.$refs.hybPay) {
							this.$refs.hybPay.isSubmitting = false;
						}

						if (pay_type == 0) {
							// 检查是否禁用接口调用
							if (!(this.$store.state.base.show_base && this.$store.state.base.show_base.jy_bb ===
									1)) {
								uni.gPost("userinfo").then((data) => {
									this.$store.commit("set_user", data);
								})
							}
						}

						uni.redirectTo({
							url: "/hyb_o2o/subpagesA/pages/order/order"
						})
					}).catch((e) => {
						// 隐藏加载提示
						uni.hideLoading();

						// 重置提交状态
						this.isSubmitting = false;
						this.lastPayType = null; // 重置支付方式记录

						// 重置支付组件的提交状态
						if (this.$refs.hybPay) {
							this.$refs.hybPay.isSubmitting = false;
						}

						// 支付失败处理
						console.error('支付失败:', e);

						// 根据支付方式显示不同的错误提示
						let errorMessage = "支付失败，请重试";
						if (pay_type === 1) { // 微信支付
							errorMessage = "微信支付失败，您可以尝试余额支付";
						} else if (pay_type === 0) { // 余额支付
							errorMessage = "余额支付失败，请检查余额是否充足";
						}

						uni.showToast({
							title: errorMessage,
							icon: 'none',
							duration: 3000
						});
					})
				}
			},

			showTip(type, info) {
				let jumpPath = '';

				// 根据类型判断是其他费用还是增值费用
				if (type === '其他费用' || type === info.goods.extra1_name) {
					// 其他费用
					if (info.goods.g_extra1 && info.goods.g_extra1.length > 0 && info.goods.g_extra1[0].tip) {
						jumpPath = info.goods.g_extra1[0].tip;
					}
				} else if (type === '增值费用' || type === info.goods.extra2_name) {
					// 增值费用
					if (info.goods.g_extra2 && info.goods.g_extra2.length > 0 && info.goods.g_extra2[0].tip) {
						jumpPath = info.goods.g_extra2[0].tip;
					}
				}

				// 如果有跳转路径，则进行页面跳转
				if (jumpPath) {
					// 检查路径是否以 / 开头，如果没有则添加
					if (!jumpPath.startsWith('/')) {
						jumpPath = '/' + jumpPath;
					}

					// 进行页面跳转
					uni.navigateTo({
						url: jumpPath,
						fail: (err) => {
							console.error('页面跳转失败:', err);
							uni.showToast({
								title: '页面跳转失败',
								icon: 'none'
							});
						}
					});
				} else {
					// 如果没有跳转路径，显示提示
					uni.showToast({
						title: '暂无相关页面',
						icon: 'none'
					});
				}
			},

			toggleSpecs(index) {
				this.expandedItems[index] = !this.expandedItems[index];
			}
		},
		onUnload() {
			// 组件销毁时清理事件监听
			uni.$off(this.tag);
			// 重置提交状态
			this.isSubmitting = false;
			this.lastPayType = null;
			// 重置支付组件的提交状态
			if (this.$refs.hybPay) {
				this.$refs.hybPay.isSubmitting = false;
			}
		},
		onHide() {
			// 页面隐藏时清理loading状态
			uni.hideLoading();
			// 重置提交状态
			this.isSubmitting = false;
			this.lastPayType = null;
			// 重置支付组件的提交状态
			if (this.$refs.hybPay) {
				this.$refs.hybPay.isSubmitting = false;
			}
		},
		computed: {
			mergedList() {
				// 展示用，合并同商品不同规格/分类/增值费用
				const map = {};
				this.list.forEach(item => {
					const gid = item.goods.g_id;
					if (!map[gid]) {
						map[gid] = {
							goods: item.goods,
							specs: [],
							extra1: [],
							extra2: [],
							// 记录原始项索引，便于交互
							_itemIndexes: []
						};
					}
					// 规格
					if (item.guige_index > -1) {
						map[gid].specs.push({
							name: item.goods.g_guigecontent[item.guige_index].name,
							price: item.goods.g_guigecontent[item.guige_index].price,
							num: item.g_num
						});
					} else {
						map[gid].specs.push({
							name: item.goods.g_guigename,
							price: item.goods.g_jiage,
							num: item.g_num
						});
					}
					// 其他费用 - 存储索引而不是对象
					if (item.extra1 && item.extra1.length && item.goods.g_extra1) {
						item.extra1.forEach(idx => {
							if (!map[gid].extra1.includes(idx)) {
								map[gid].extra1.push(idx);
							}
						});
					}
					// 增值费用 - 存储索引而不是对象，修复：即使extra2为空也要处理
					if (item.goods.g_extra2 && item.goods.g_extra2.length) {
						// 如果item.extra2不存在，初始化为空数组
						if (!item.extra2) {
							item.extra2 = [];
						}
						// 处理已选择的增值费用
						if (item.extra2.length > 0) {
							item.extra2.forEach(idx => {
								if (!map[gid].extra2.includes(idx)) {
									map[gid].extra2.push(idx);
								}
							});
						}
					}
					map[gid]._itemIndexes.push(this.list.indexOf(item));
				});
				return Object.values(map);
			}
		}
	}
</script>

<style>
	/* 自定义较小的圆角样式，替代 gui-border-radius-large */
	.pay-card-radius {
		border-radius: 7rpx !important;
	}

	/* 自定义容器样式，替代 gui-margin-x-middle */
	.pay-container {
		margin-left: -10rpx !important;
		margin-right: -10rpx !important;
	}
</style>